<?php

class DefaultController extends BaseController {
    
    public $advertCode;
    
    private function setAdvert($catId) {
        $this->advertCode = Yii::app()->db->createCommand()->select('b.code')->from('banners_relations r')->join('banners b', 'b.bannerId=r.bannerId and b.type="Спонсор категории на главной" ')->where('r.catId='.$catId)->queryScalar();
    }
    
    public function actionCalendar() {
        $pagination = new CPagination(Partner::model()->count());
        $pagination->setPageSize(30);
        $partners = Partner::model()->pagination($pagination->getLimit(), $pagination->getOffset())->with('cat.parent')->findAll(array('order'=>'openDate DESC, isClose ASC'));
        $this->render('calendar', array('partners'=>$partners, 'pagination'=>$pagination));
    }
    
    public function actionCat($catId, $parentId=0) {
        $cat = Yii::app()->db->createCommand()->select('*')->from('partners_cat')->where("catId=$catId and parentId=$parentId")->queryRow();
        if(empty($cat)) throw new CHttpException(404, 'Не найдено указанной записи');
        $this->brending('cat', $catId, $parentId);
        if($cat['parentId']) {
            $catSubCats = Yii::app()->db->createCommand()->select('catId, name, parentId')->from('partners_cat')->where('parentId='.$cat['parentId'])->queryAll();
            $subcatRel = Yii::app()->db->createCommand()->select('partnerId')->from('partners_sub_cat_rel')->where("catId=$catId")->queryAll();
            $pId = array();
            for($i=0; $i<count($subcatRel); $i++) $pId[] = $subcatRel[$i]['partnerId'];
            $partners = Yii::app()->db->createCommand()->select('p.url, p.partnerid, p.isClose, p.name, p.editorMark, p.catId, p.openDate, p.openDate, p.about, p.zeroPosition, s.mean, s.field1, s.field2, s.field3, s.field4, s.oldMean, s.oldField1, s.oldField2, s.oldField3, s.oldField4, s.votes')->from('partners p')->leftJoin('partners_cat_score s', 's.partnerId=p.partnerid')->where(array('in', 'p.partnerid', $pId))->order('p.isClose asc')->queryAll();
        } else {
            $catSubCats = Yii::app()->db->createCommand()->select('catId, name, parentId')->from('partners_cat')->where('parentId='.$cat['catId'])->queryAll();
            $partners = Yii::app()->db->createCommand()->select('p.url, p.partnerid, p.name, p.isClose, p.editorMark, p.catId, p.openDate, p.openDate, p.about, p.zeroPosition, s.mean, s.field1, s.field2, s.field3, s.field4, s.oldMean, s.oldField1, s.oldField2, s.oldField3, s.oldField4, s.votes')->from('partners p')->leftJoin('partners_cat_score s', 's.partnerId=p.partnerid')->where('p.catId='.$catId)->order('p.isClose asc')->queryAll();
        }
        if(!empty($partners)) {
            $idArr = array();
            for($j=0; $j<count($partners); $j++) $idArr[] = $partners[$j]['partnerid'];
            $subCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where('rc.partnerId in('.implode(',',$idArr).') and rc.catId<>'.$catId)->queryAll();
            for($i=0; $i<count($partners); $i++) {
                if($partners[$i]['zeroPosition']) {
                    $cat['zeroPart'][] = $partners[$i];
                    continue;
                }
                $subStr = '';
                $partners[$i]['subcats'] = array();
                if(!empty($subCats)) {
                    for($l=0; $l<count($subCats); $l++) {
                        if($subCats[$l]['partnerId'] == $partners[$i]['partnerid']) $partners[$i]['subcats'][] = $subCats[$l]; 
                    }
                    if(!empty($partners[$i]['subcats'])) {
                        $subStr ='<ul  class="inline unstyled home_subcats">';
                        for($n=0; $n<count($partners[$i]['subcats']); $n++) { 
                            $subStr .= '<li class="subcats'.$n.'">'.CHtml::link($partners[$i]['subcats'][$n]['name'], Yii::app()->createUrl('partner/default/cat', array('catId'=>$partners[$i]['subcats'][$n]['catId'], 'parentId'=>$partners[$i]['subcats'][$n]['parentId']))).'</li>&nbsp;&nbsp;';
                        }
                        $subStr.="</ul>";
                    }
                }
                if($parentId) $url = Yii::app()->createUrl('partner/profile/index', array('catId'=>$cat['parentId'], 'partnerUrl'=>$partners[$i]['url']));
                else $url = Yii::app()->createUrl('partner/profile/index', array('catId'=>$cat['catId'], 'partnerUrl'=>$partners[$i]['url']));
                $data[] = array('partnerName'=>$partners[$i]['name'], 'parentId'=>$cat['parentId'], 'id'=>$partners[$i]['partnerid'], 'catId'=>$cat['catId'], 'field1'=>$partners[$i]['field1'], 'field2'=>$partners[$i]['field2'], 'dateOpen'=>date("d.m.Y", $partners[$i]['openDate']), 'field3'=>$partners[$i]['field3'], 'field4'=>$partners[$i]['field4'], 'mean'=>$partners[$i]['mean'], 'oldMean'=>$partners[$i]['oldMean'], 'relCats'=>$subStr, 'url'=>$url, 'votes'=>$partners[$i]['votes'], 'editorMark'=>$partners[$i]['editorMark'], 'close'=>$partners[$i]['isClose']);
            }
        }
        $dataProvider = new CArrayDataProvider(!empty($data) ? $data : array(), array(
            'sort'=>array('attributes'=>array('partnerName', 'field1', 'field2', 'field3', 'field4', 'mean', 'editorMark', 'dateOpen', 'close'), 'defaultOrder'=>array('close'=>false)), 'pagination'=>array('pageSize'=>25)
        ));
        $relPartners = Yii::app()->db->createCommand()->select('s.mean, p.countComments, p.about, p.catId, c.name as catName, p.name, p.url, s.votes')->from('partners_relcat prc')->join('partners p', 'p.partnerid=prc.partnerid')->join('partners_cat c', 'c.catId=p.catId')->leftJoin('partners_cat_score s', 's.partnerId=p.partnerid')->where('prc.relCatId='.$catId.' and p.isClose=0')->queryAll();
        $lastThemes = Yii::app()->db->createCommand()->select('ft.title, ft.url, p.url as partnerUrl, c.catId, c.parentId')->from('forum_theme ft')->join('partners p', 'p.partnerid=ft.partnerId')->join('partners_cat c', 'c.catId=p.catId')->where('1')->limit(5)->order('ft.date DESC')->queryAll();
        $lastPosts = Yii::app()->db->createCommand()->select('u.login, u.displayName, t.themeId, t.title, t.countComments, fc.text, p.url, c.catId, c.parentId')->from('forum_comments fc')->join('forum_theme t', 't.themeId=fc.themeId and isFirst=0')->join('partners p', 'p.partnerid=t.partnerId')->join('partners_cat c', 'c.catId=p.catId')->join('users u', 'u.userid=fc.userId')->where(1)->limit(5)->order('fc.comDate DESC')->queryAll();
        $this->setAdvert($parentId ? $parentId : $catId);
        $this->render('category', array('partners'=>$partners, 'catSubCats'=>$catSubCats, 'lastPosts'=>$lastPosts, 'lastThemes'=>$lastThemes, 'cat'=>$cat, 'parent'=>isset($parent) ? $parent : 0, 'relPartners'=>$relPartners, 'dataProvider'=>$dataProvider));
    }
    
    public function actionTopForums($catId) {
        $cat = Yii::app()->db->createCommand()->select('catId,parentId, about')->from('partners_cat')->where('catId='.$catId)->queryRow();
        if(empty($cat)) throw new CHttpException(404, 'Не найдено указанной записи');
        $pagination = new CPagination(Partner::model()->count("`t`.`catId`=$catId"));
        $option = Yii::app()->db->createCommand()->select('val')->from('options')->where('name="количество форумов в ТОП"')->queryScalar();
        $pagination->setPageSize(!empty($option) ? $option : '30');
        if($cat['parentId']) {
            $forums = Partner::model()->with('cat')->pagination($pagination->getLimit(), $pagination->getOffset())->findAll(array('select'=>'name, url, countComments', 'condition'=>"`t`.`catId`=".$cat['parentId'], 'order'=>'countComments DESC'));
        } else {
            $forums = Partner::model()->with('cat')->pagination($pagination->getLimit(), $pagination->getOffset())->findAll(array('select'=>'name, url, countComments', 'condition'=>"`t`.`catId`=$catId", 'order'=>'countComments DESC'));
        }
        if(!isset($forums)) throw new CHttpException(404, 'Не найдено указанной записи');
        if($cat['parentId']) {
            $catSubCats = Yii::app()->db->createCommand()->select('catId, name, parentId')->from('partners_cat')->where('parentId='.$cat['parentId'])->queryAll();
        } else {
            $catSubCats = Yii::app()->db->createCommand()->select('catId, name, parentId')->from('partners_cat')->where('parentId='.$catId)->queryAll();
        }
        $this->setAdvert($cat['parentId'] ? $cat['parentId'] : $catId);
        $this->render('topForums', array('forums'=>$forums, 'catSubCats'=>$catSubCats, 'pagination'=>$pagination, 'cat'=>$cat));
    }
    
    public function actionAllTopForums() {
        $pagination = new CPagination(Partner::model()->count(1));
        $option = Yii::app()->db->createCommand()->select('val')->from('options')->where('name="количество форумов в ТОП"')->queryScalar();
        $pagination->setPageSize(!empty($option) ? $option : '30');
        $forums = Partner::model()->with('cat')->pagination($pagination->getLimit(), $pagination->getOffset())->findAll(array('select'=>'name, url, countComments', 'order'=>'countComments DESC'));
        $this->render('allTopForums', array('pagination'=>$pagination, 'forums'=>$forums));
    }
}